package fun.lifepoem.files.service;

import fun.lifepoem.domain.RestResponse;
import fun.lifepoem.service.common.BaseService;
import fun.lifepoem.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * @author Yiwyn
 * @create 2022/7/24 0:17
 */
@Service
public class FilesService extends BaseService {

    @Value("${file-warehouse.host}")
    private String domain;

    @Value("${file-warehouse.prefix}")
    private String prefix;

    @Value("${file-warehouse.resourceLocation}")
    private String location;

    public String hello() {
        return "hello";
    }

    public RestResponse<String> upload(MultipartFile file) {

        /**
         * 1.接收到的文件进行文件名和文件后缀进行单独分离
         * 2.生成本地存储位置 url
         * 3.将数据保存到数据库
         */

        String originalFilename = file.getOriginalFilename();


        String[] split = originalFilename.split("\\.");

        //获取扩展名
        String extendName = split[split.length - 1];

        String fileName = SnowFlakeUtil.getInstance().getSnowId() + "." + extendName;

        String path = location + fileName;

        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return doError(e.getMessage());
        }

        String url = domain + prefix + fileName;

        return doSuccess(url);
    }


}
